package com.tebiecloud.mpopen.server.controller;

import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.common.utils.WebUtils;
import com.tebiecloud.mpopen.server.service.MpopenCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 第三方平台回调接口
 * @Author: tebie
 * @Date: 2019-09-07 16:07
 */
@Slf4j
@RestController
@RequestMapping(value = "/mpopencallback")
public class MpopenCallbackController {

    @Autowired
    private MpopenCallbackService mpopenCallbackService;

    /**
     * 事件推送回调接口
     * @param request
     * @return
     */
    @PostMapping(value = "/event")
    public Object event(HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("UTF-8");

        String msgSignature = request.getParameter("msg_signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        if(StringUtils.isEmpty(msgSignature) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(nonce)) {
            log.error("xiaoc>> 第三方平台事件推送请求参数错误, msgSignature: " + msgSignature + ", timestamp: " + timestamp + ", nonce: " + nonce);
        } else {
            String body = WebUtils.getBodyString(request);
            mpopenCallbackService.event(msgSignature, timestamp, nonce, body);
        }

        return "success";
    }

    /**
     * 第三方回调公众号消息
     * @param request
     * @return
     */
    @PostMapping(value = "/msgreceive/{appid}")
    public Object msgReceive(@PathVariable String appid, HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("UTF-8");

        String msgSignature = request.getParameter("msg_signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        if(StringUtils.isEmpty(msgSignature) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(nonce)) {
            log.error("xiaoc>> 第三方平台公众号消息推送请求参数错误, msgSignature: {}, timestamp: {}, nonce: {}", msgSignature, timestamp, nonce);
        } else {
            String body = WebUtils.getBodyString(request);
            mpopenCallbackService.msgReceive(appid, msgSignature, timestamp, nonce, body);
        }

        return "success";
    }

}
